<?php
/** 
 * Database model for the "box" object
 *
 * Boxes are simplified content types that just have names and content. They
 * are meant to be used in templates in places where the content is mostly static
 * but the user may want to change it on occasion. Boxes are not accessible
 * via URL and are only viewable when included in a template
 *
 * @package Concerto
 * @subpackage Models
 * @author Jason Raede <jason@torchdm.com>
 */
namespace application\models;
use application\utilities\Utility;
class Box extends DBObject {
	
	/**
	 * The name of the box
	 * 
	 * @var string
	 */
	protected $name;
	
	/**
	 * The content of the box
	 *
	 * @var string
	 */
	protected $content;
	
	/**
	 * The database ID of the box
	 *
	 * @var int
	 */
	protected $id;
	
	/**
	 * Initializes the values if an ID is provided
	 *
	 * @param int $id The box's database ID
	 */
	public function __construct($id = null) {
		if($id) {
			$row = DB()->getRow("SELECT * FROM `cn_boxes` WHERE `box_id`='$id'");
			$this->name = $row->box_name;
			$this->content = $row->box_content;
			$this->id = $id;
		}
	}
	
	/**
	 * Set the box's properties based on the given parameters
	 *
	 * @param array $params An array of parameters. Accepts all properties except ID
	 */
	public function create($params) {
		// Needs a name and content
		if(!$params['name'] || !$params['content']) {
			Utility::triggerError('Boxes must have a name and content.');
		}
		else {
			$this->name = $params['name'];
			$this->content = $params['content'];
		}
	}
	
	/**
	 * Adds the box to the database or updates its row, depending upon whether or not
	 * its ID property is set
	 *
	 * @return array An array of error and success messages
	 */
	public function save() {
		$return = array();
		$db = array('box_name'=>$this->name, 'box_content'=>$this->content);
		// Make sure there's not already a box with this name
		if(DB()->getCount("SELECT `box_id` FROM `cn_boxes` WHERE `box_name`='$this->name' AND `box_id` !='$this->id'")) {
			$return['errors'][] = 'Box must have a unique name';
		}
		else if($this->id) {
			DB()->update('cn_boxes', 'box_id', $this->id, $db);
			$return['successes'][] = 'Box updated successfully.';
		}
		else {
			DB()->insert('cn_boxes', $db);
			$this->id = DB()->lastInsert();
			$return['successes'][] = 'Box created successfully.';
		}	
		
		return $return;
	}
	
	/**
	 * Deletes the box from the database
	 */
	public function delete() {
		DB()->query("DELETE FROM `cn_boxes` WHERE `box_id`='$this->id'");
	}
}